#pragma once

#include <entt/entt.hpp>

#include <string>
#include <unordered_map>
#include <vector>

#include "qlib/all.h"

#include "../../render/components.hpp"
#include "../components.hpp"

namespace qbe::draw::pin {

enum struct State { None = 0, Wait, Upatde, Complete, Cancel };
struct Models {
  qlib::Pin::s_ptr cache_pin;
  render::LineListMesh mesh;

  State state = State::None;
  entt::entity entity = entt::null;
  entt::entity complete_entity = entt::null;

  // std::vector<std::string> string_arr;
  // int count = 0;

  bool clear_tag = false;
  bool is_first_ui = true;
  bool first_open = false;

  uint32_t id = 100;
  std::string str = "";
  qlib::PinType type;
  double rotation = 0;
  std::unordered_map<uint32_t, bool> id_use_map;

  void flushMap(entt::registry& reg) {
    auto view = reg.view<qlib::Pin::s_ptr>();
    id_use_map.clear();

    view.each([&](entt::entity e, qlib::Pin::s_ptr pin) {
      if (e != entity) {
        id_use_map[pin->getId()] = true;
      }
    });
  }

  uint32_t getId() {
    uint32_t max_id = 1;
    auto it = id_use_map.begin();

    while (it != id_use_map.end()) {
      if (it->second && it->first + 1 > max_id) {
        max_id = it->first + 1;
      }
      it++;
    }

    return max_id;
  }

  void update() {
    if (id_use_map[id]) {
      id = getId();
      str = std::to_string(id);
    }
  }

  void update(uint32_t id) {
    id_use_map[id] = true;
    update();
  }
};
}  // namespace qbe::draw::pin